package ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import ejb.entity.Notification;
import ejb.entity.Position;

@Stateless
public class DefaultNotificationDAO implements NotificationDAO {

	@PersistenceContext
	EntityManager em;
	
	@Override
	public Notification create(Notification notification) {
		try{
			em.persist(notification);
		}catch(IllegalArgumentException e){
			return null;
		}
		return notification;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Notification> findAll() {
		try{
			List<Notification> n = (List<Notification>)em
					.createNamedQuery("DefaultNotification.findAll")
					.getResultList();			
			return n;
		}catch(NoResultException nre){
			return null;
		}
	}	

	@Override
	public Notification findById(int id) {
		Notification n = (Notification)em
				.createNamedQuery("DefaultNotification.findById")
				.setParameter("id", id)
				.getSingleResult();
		return n;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Notification> findByPosition(Position pos) {
		try{
			List<Notification> n = (List<Notification>)em
					.createNamedQuery("DefaultNotification.findPositionNotifications")
					.setParameter("pos", pos)
					.getResultList();
			return n;
		}catch(NoResultException nre){
			return null;
		}
	}
	
	@Override
	public boolean delete(Notification notification) {
		try{
			em.remove(notification);
		}catch(IllegalArgumentException e){
			return false;
		}
		return true;
	}
	
}
